Working with the XmlNode class in C#

In the previous section, we used the XmlDocument class to parse the XML file. In the example a new class was introduced, which is very important for parsing XML with XMLDom: XMLNode class XML is basically parsed in an XMLNode which is the basic element and after that you use the hair elements By doing the hair can reach the elements. However, the XMLNode class gives you access to many other information, for example tags, properties, internal text and XML This chapter is a brief description of some more interesting aspects of the XmlNode class, which is important to know about it because the XmlNode class XmlDocument is an important concept when parsing XML with square. In the following examples we will use DocumentElement a lot, and when it is within the scope of XML type, XMLAllment gets inherited from XMLNode, so it is essentially similar.

Name property will only give you the name of the node. For example, the following example "user" will output the text:


XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<user name=\"Sandy Doe\">A user node</user>");
Console.WriteLine(xmlDoc.DocumentElement.Name);
Console.ReadKey();

The InnerText property will hold the text contained within the starting and the ending tag, like this:


XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<test>InnerText is here</test>");
Console.WriteLine(xmlDoc.DocumentElement.InnerText);
Console.ReadKey();

The InnerXml property is a bit like the InnerText property, but while InnerText will strip out any XML within it, the InnerXml property obviously won't. The following example should illustrate the difference:


XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<users><user>InnerText/InnerXml is here</user></users>");
Console.WriteLine("InnerXml: " + xmlDoc.DocumentElement.InnerXml);
Console.WriteLine("InnerText: " + xmlDoc.DocumentElement.InnerText);
Console.ReadKey();

The OuterXml property is the same as the InnerXml, but it will include the XML of the node itself as well. The following example should illustrate the difference:


XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<users><user>InnerText/InnerXml is here</user></users>");
Console.WriteLine("InnerXml: " + xmlDoc.DocumentElement.InnerXml);
Console.WriteLine("OuterXml: " + xmlDoc.DocumentElement.OuterXml);
Console.ReadKey();

We worked with attributes in the previous chapter, but here is another example:


XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<user name=\"Sandy Doe\" age=\"42\"></user>");
if(xmlDoc.DocumentElement.Attributes["name"] != null)
    Console.WriteLine(xmlDoc.DocumentElement.Attributes["name"].Value);
if(xmlDoc.DocumentElement.Attributes["age"] != null)
    Console.WriteLine(xmlDoc.DocumentElement.Attributes["age"].Value);
Console.ReadKey();